package cn.b.sky.form.form;

import cn.b.sky.form.constans.CustomerPageConstans;
import cn.b.sky.form.form.builder.FormBuilder;
import cn.b.sky.form.model.Screen;
import freemarker.core.Environment;
import freemarker.ext.beans.StringModel;
import freemarker.template.*;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

/**
 * 
 * <strong>Title : FormDirective.java<br></strong>
 * <strong>Package : cn.b.sky.form.form<br></strong>
 * <strong>Description : form表单生成器</strong><br> 
 * <strong>Create on : 2016-11-8 下午4:03:30<br></strong>
 * <p>
 * @author lidapeng<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 * <strong>修改历史:</strong><br>
 * 修改人|修改日期|修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
public class FormDirective implements TemplateDirectiveModel {

  @Override
  public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
      throws TemplateException, IOException {

    if (loopVars.length != 0) {
      throw new TemplateModelException("This directive doesn't allow loop variables.");
    }
    // 真正开始处理输出内容  
    Writer out = env.getOut();
    TemplateModel tm = env.getVariable(CustomerPageConstans.SCREEN_PARAM);
    Screen screen = (Screen) ((StringModel)tm).getWrappedObject();
    
    String value = FormBuilder.toHtmlElement(screen);
    if (body != null) {
      if (!StringUtils.isBlank(value)) {
        out.write(value);
      } else {
        body.render(out);
      }
    } else {
      out.write(value);
    }
  }

}
